﻿using Hx.ADSyncPlatform.Common.Log;
using Hx.ADSyncPlatform.Entity.Entities;
using Hx.ADSyncPlatform.Infrastructure.Exceptions;
using Hx.ADSyncPlatform.WebApi.Model;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Hosting;
using System.Net;

namespace Hx.ADSyncPlatform.Filter
{
    public class GlobalExceptionFilter : IExceptionFilter
    {
        private IWebHostEnvironment _env;
        private readonly LogHelper logHelper;
        private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
        public GlobalExceptionFilter(IWebHostEnvironment _env, LogHelper logHelper)
        {
            this._env = _env;
            this.logHelper = logHelper;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public void OnException(ExceptionContext context)
        {
            var json = new Result<string>();

            if (_env.IsDevelopment())
            {
                json.data = context.Exception.StackTrace;//堆栈信息
            }
            json.success = false;
            json.status = 500;
            json.msg = context.Exception.Message;

            if (context.Exception is BizException)
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.OK;
                context.ExceptionHandled = true;
            }
            else
            {
                var ex = context.Exception;
                logger.Error(ex);
                logHelper.WriteToDb(BehaviorType.Exception, ex.Message + "   " + ex.Source + "   " + ex.Data + "  " + ex.StackTrace);
            }
            context.Result = new JsonResult(json);
        }
    }
}
